package by.grsu.na.dao.impl;

import java.io.Serializable;
import java.util.List;




import by.grsu.na.entity.Client;
import by.grsu.na.table.ClientTable;

import com.epam.grsulab.webapi.dao.AbstractDao;


public class ClientDao extends AbstractDao<ClientTable, Client> {

	public ClientDao(final String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public void saveNew(final Client newClient) {

		newClient.setId(getNextId());

		final ClientTable clientTable = deserializeFromXml();

		clientTable.getRows().add(newClient);

		serializeToXml(clientTable);
	}

	@Override
	public void update(final Client entity) {

		final ClientTable clientTable = deserializeFromXml();

		for (final Client row : clientTable.getRows()) {
			if (row.getId().equals(entity.getId())) {

				
				row.setClientName(entity.getClientName());
				row.setClientLogin(entity.getClientLogin());
				row.setClientPasword(entity.getClientPasword());
				break;
			}
		}

		serializeToXml(clientTable);
	}

	@Override
	public Client get(final Serializable id) {

		final ClientTable clientTable = deserializeFromXml();

		for (final Client row : clientTable.getRows()) {
			if (row.getId().equals(id)) {
				return row;
			}
		}
		return null;
	}

	@Override
	public List<Client> getAll() {

		final ClientTable clientTable = deserializeFromXml();
		return clientTable.getRows();
	}

	@Override
	public void delete(final Serializable id) {

		final ClientTable clientTable = deserializeFromXml();

		Client toBeDeleted = null;
		for (final Client row : clientTable.getRows()) {
			if (row.getId().equals(id)) {

				toBeDeleted = row;
				break;
			}
		}

		clientTable.getRows().remove(toBeDeleted);

		serializeToXml(clientTable);
	}

	@Override
	protected Class<ClientTable> getTableClass() {
		return ClientTable.class;
	}

}
